import * as tokenUtils from "../utils/jwt-utils";
import { Request, Response, NextFunction } from "express";
import { responseHandler, errorHandler, paramsHandler } from "../utils/handler-utils";


interface TokenUser {
  userId: string;
  account: string;
}

// 将 Request 接口扩展，增加 state 属性，存储用户信息
export interface AuthenticatedRequest extends Request {
  state?: {
    userInfo: TokenUser;
  };
}

// 编写一个中间件，用于验证用户是否登录
export const auth = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
) => {
  const { headers } = req;
  const { authorization } = headers;

  // 此处直接预置了Bearer，不用加了
  const token = (authorization as string)?.replace("Bearer ", "");

  // 缺少token
  if (!token) {
    responseHandler({
      httpStatus: 401,
      code: 1,
      message: "缺少 token",
      req,
      res,
    });
    return;
  }

  // 如果前端发的请求带了 token，就验证 token，将用户信息存储到 state 中
  const verifyJwt = tokenUtils.verifyJwtAccessToken(token);
  if (verifyJwt.valid == false) {
    if (verifyJwt.error.name === "TokenExpiredError") {
      errorHandler({
        error: verifyJwt.error,
        httpStatus: 401,
        message: "登录过期，请重新登录",
        req,
        res,
      });
    } else {
      errorHandler({
        error: verifyJwt.error,
        httpStatus: 401,
        message: "该token无效，请重新登录",
        req,
        res,
      });
    }
    return;
  } else {
    req.state = { userInfo: {} as TokenUser };
    req.state.userInfo = verifyJwt as TokenUser;
  }
  next();
};
